"""
imgtp图床工具包
"""
from application.exception.BasicException import BasicException
from application.config.ImageUploadConfig import ImageBedConfig
from application.util.StatusCode import StatusCode
from application.util.RedisUtil import RedisUtil
from typing import Optional
from httpx import Response
import httpx

# 图床API接口
host: str = "https://www.imgtp.com/api"
# 实例化redis工具
redis_util: RedisUtil = RedisUtil()
client: httpx.Client = httpx.Client(timeout=None)  # 永不超时


def get_token() -> str:
    """
    获取Token
    :return: token
    """
    # Redis中token的key
    redis_token_key: str = "imgtp_token"
    # 从redis中获取token
    token: Optional[str] = redis_util.get_value(key=redis_token_key)
    # token存在，则直接返回
    if token:
        return token
    url: str = f"{host}/token"
    payload: dict = {
        "email": ImageBedConfig.email,
        "password": ImageBedConfig.password
    }
    response: Response = client.post(url=url, data=payload)
    if response.status_code != 200 or response.json().get("code") != 200:
        raise BasicException(status_code=StatusCode.FILE_UPLOAD_ERROR.value, error_message="获取Token失败，稍后再试")
    token: str = response.json().get("data").get("token")
    redis_util.set_value(key=redis_token_key, value=token, ex=60 * 60 * 24 * 7)  # token有效期7天
    return token


def upload_image(files: list) -> dict:
    """
    上传图片
    :param files: 文件对象列表：[("file",(image_storage.filename, image_io, "image/*"))]
    :return: 上传返回值: {
        "id": "135936",
        "name": "2024030515565.jpg",
        "url": "https://img2.imgtp.com/2024/03/14/Vhz2VWJQ.jpg",
        "size": 944870,
        "mime": "image/jpeg",
        "sha1": "64093c699d1c0dee549aeee79c6a19d95101b711",
        "md5": "af19d175051c4f011334431379352e72",
        "quota": "32212254720.00",
        "use_quota": "944870.00"
    }
    """
    headers: dict = {
        "token": get_token()
    }
    url: str = f"{host}/upload"
    response: Response = client.post(url=url, files=files, headers=headers, timeout=10)
    if response.status_code != 200 or response.json().get("code") != 200:
        raise BasicException(status_code=StatusCode.FILE_UPLOAD_ERROR.value, error_message="上传图片失败，稍后再试")
    return response.json().get("data")


def delete_image(unique_id: str) -> None:
    """
    删除图片
    :param unique_id: 第三方ID
    :return:
    """
    headers: dict = {
        "token": get_token()
    }
    url: str = f"{host}/delete"
    response: Response = client.post(url=url, data={"id": unique_id}, headers=headers, timeout=10)
    if response.text.find("删除成功") == -1:
        raise BasicException(status_code=StatusCode.FILE_DELETE_ERROR.value, error_message="删除图片失败，稍后再试")
